package 力扣;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 示例：
 二叉树：[3,9,20,null,null,15,7],
   3
  / \
 9  20
   /  \
  15   7
 返回其层次遍历结果：
 [
 [3],
 [9,20],
 [15,7]
 ]
 */
public class _102二叉树的层序遍历 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    //队列实现
    public List<List<Integer>> levelOrder(TreeNode root) {
        if( root == null ) return new ArrayList<List<Integer>>();
        LinkedList<TreeNode> quque = new LinkedList<>();
        ArrayList<List<Integer>> lists = new ArrayList<>();
        quque.add(root);
        while( !quque.isEmpty()){
            // 获取改层的节点数
            int size = quque.size();
            List<Integer> list = new ArrayList<Integer>();
            while( size > 0 ){
                TreeNode node = quque.poll();
                list.add(node.val);
                if( node.left != null ){
                    quque.add(node.left);
                }
                if( node.right != null ){
                    quque.add(node.right);
                }
                size--;
            }

            lists.add(list);
        }

        return lists;
    }

}
